<template>
	<view>
		
		<view class='detail-top'>
		    <view class='time time-black'>订单号: {{ order.no}}</view>
		    <view class='time time-black'>下单时间: {{ order.ctime*1000 | formatDate}}</view>
			<view class='time time-black'>共{{order.order.length}}种商品</view>
			<view class='time time-black'>0种商品已收到</view>
		</view>
		
		<view class="divider-detail"></view>
		
		<scroll-view scroll-y="true" class="scroll-base" :style="'height:'+clientHeight+'px'">
		<block v-for="(goodsItem, goodsIndex) in order.order" :key="goodsIndex" >
		
		  <view class='detail-item'>
			<view class="flex-wrap flex-direction-row">
				<image style="margin-right: 36rpx;" class="goodsimg" :src='goodsItem.goodsImages.path'></image>
				<view style="width: 450rpx;">
					  <view class='dish-title'>{{ goodsItem.productName}}&nbsp;&nbsp;|&nbsp;&nbsp;{{goodsItem.unit || '斤'}}</view>
					  <view class='detail-plus' style="width: ;">
					  {{ goodsItem.goodsInfo.detail || '测试详情测试详情测试详情测试详情测试详情测试详情' }}</view>
				</view>
			</view>
			<view class="flex-wrap flex-direction-row" style="margin-top: 6px;">
				<view style="width: 94px;"></view>
				<view class='time flex-item'>发货小结:</view>
				<view class='time flex-item'>¥{{goodsItem.price/100}}</view>
				<view class='time flex-item'>×{{goodsItem.qty}}</view>
				<view class='time flex-item'>¥{{goodsItem.subtotal/100}}</view>
			</view>
			<view v-if="goodsItem.status > 3" class="flex-wrap flex-direction-row">
				<view style="width: 94px;"></view>
				<view class='time time-black flex-item'>签收小结:</view>
				<view class='time time-black flex-item'>¥{{goodsItem.signforPrice/100}}</view>
				<view class='time time-black flex-item'>×{{goodsItem.signforQty}}</view>
				<view class='time time-black flex-item'>¥{{goodsItem.signforSubtotal/100}}</view>
			</view>
			
			<view v-if="goodsItem.status == 4"  style="margin-left: 94px;">
				<view class='time time-black flex-item'>
					签收时间:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{goodsItem.signforTime}}
				</view>
				<view class='time time-black flex-item'>
					签收证明:
				</view>
				<view class="row-wrap" v-for="(item, index) in showPhotoes" :key="index" >
					<image class="select-photo" :src="item"></image>
				</view>
			</view>
			
			<view class="flex-wrap flex-direction-row" style="margin-top: 10px">
				<view class="exception" :style="'background-color:'+colorMap[goodsItem.status]">{{statusMap[goodsItem.status]}}</view>
				<view style="flex:1" ></view>  
				<button :disabled="goodsItem.status < 3 || goodsItem.status > 4"  @click.stop="confirm(goodsItem.id, goodsIndex, goodsItem.status)" 
				:class="['route', 'confirm', goodsItem.status == 4 ? 'comment' : '']" 
				hover-class="confirm-hover">{{goodsItem.status < 4 ? '确定收货':'退货'}}</button>
			</view>
				
		  </view>
			 
		</block>
		</scroll-view>
		
		<modal v-if="showPop" title="不输入则和发货(单价/数量)一致" confirm-text="确定" 
		cancel-text="取消" @cancel="cancelPop" @confirm="cancelPop"> 
			<input type='number' @input="inputSignQty" placeholder-class="time" placeholder="请输入签收数量"  />
			<input type='number' @input="inputSignPrice"  placeholder-class="time" placeholder="请输入签收单价"  />
			<view class="uploadImage">
				<image v-if="selectedPhotoes.length < 6" @click="selectPhoto" class="select-photo plus-border" src="../../../static/my/plus.png"></image> 
				<view class="row-wrap" v-for="(item, index) in selectedPhotoes" :key="index" >
					<image class="select-photo" :src="item"></image>
				</view>
			</view>
			<button @click="uploadPhoto()">上传照片</button>
		</modal>
		
		<modal v-if="showReturn" :title="returnTitle" confirm-text="确定"
		cancel-text="取消" @cancel="noReturn" @confirm="yesReturn"> 
			<input type='number' v-model="inputReturnQty" placeholder-class="time" placeholder="请输入退货数量,不输入则和签收一样"  />
			<input type='number' v-model="inputReturnPrice"  placeholder-class="time" placeholder="请输入退货单价,不输入则和签收一样"  />
			<input v-model="returnReason" placeholder-class="time" placeholder="请输入退货原因"  />
		</modal>
		
	</view>
</template>

<script>
	var currentID = -1
	var currentIndex = -1
	var successUpLoad = 0
	
	
	export default {
		data() {
			return {
				order: {},
				clientHeight: 0,
				buttonMap: { 1:"确定收货",2:"确定收货", 3:"确定收货", 4:"退货", 5:"已退货"},
				statusMap : { 2:"待发货", 3:"已发货", 4:"已完成", 5:"已退货"},
				colorMap : {2:"#ff5f19", 3:"#999900", 4:"#0a810a", 5:"#030303"},
				showPop:false, //弹窗
				signQty: '',
				signPrice: '',
				inputReturnQty: '',
				inputReturnPrice: '',
				
				showReturn: false,
				returnTitle: '',
				returnReason: '',
				selectedPhotoes: [],
				showPhotoes: [],
				
				failUpload : 0
			}
		},
		onLoad(options) {
			
			let that = this
			let order = JSON.parse(decodeURIComponent(options.order))
			uni.getSystemInfo({
				success: function (res) {
					that.clientHeight= res.windowHeight - 148 
				}
			})
			this.order =  order 
		},
		methods: {
			
			inputSignQty:function(e){ this.signQty = e.detail.value },
			inputSignPrice:function(e){ this.signPrice = e.detail.value },
			
			cancelPop() {
				this.showPop = false
				this.signItem()
			},
			
			checkOrderStatus() {
				for (let item of this.order.order){ 
					if (item.status != 4) return 3 
				}
				return 4
			},
			
			selectPhoto(){
				let _this = this
				uni.chooseImage({
					count: 6, // 默认6
					sizeType: ['compressed', 'original'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						_this.selectedPhotoes.push(res.tempFilePaths[0])
					}
				})
			},
			
			generateKey() {
				var timestamp = new Date().getTime()
				var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
				var arr = str.split('')
				var result = ''
				for (var i = 0; i < 8; i++) {
				  var n = Math.floor(Math.random() * arr.length)
				  result += arr[n]
				}
				return result + timestamp
			},
			
			resetNumbers(){
				this.selectedPhotoes = []
				// this.showPhotoes = []
				this.failUpload = 0
				successUpLoad = 0
			},
			
			sendImageURLtoBase(url){
				let _this = this
				uni.request({
					url: _this.$common.serverAddr +'/sales/order/item/images/add',
					data: {
						"path":url,
						"itemId": currentID,
						"seq": 1
					},
					method: 'POST',
					success: function(res) {
						if(res.data.status == 200){
							successUpLoad++
							if (successUpLoad+_this.failUpload == _this.selectedPhotoes.length){
								let text = _this.failUpload == 0 ? '上传成功' : _this.failUpload+'张上传失败,请重试'
								_this.$uniApi.tipMsg(text)
								_this.resetNumbers()
							}
						}else{
							_this.failUpload++
							if (successUpLoad+_this.failUpload == _this.selectedPhotoes.length){
								_this.$uniApi.tipMsg(_this.failUpload+'张上传失败,请重试')
								_this.resetNumbers()
							}
						}
					},
					fail:function(res){
						_this.failUpload++
						if (successUpLoad+_this.failUpload == _this.selectedPhotoes.length){
							_this.$uniApi.tipMsg(_this.failUpload+'张上传失败,请重试')
							_this.resetNumbers()
						}
					}
				})
			},
			
			uploadPhoto(){
				let _this = this
				uni.request({
				  url: _this.$common.serverAddr +'/goods/info/getToken',
				  method: 'POST',
				  success: function(res) {
						console.log(res.data.data)
						for (var imageUrl of _this.selectedPhotoes) {
							var key = _this.generateKey()
							uni.uploadFile({
							    url: 'https://up-z2.qiniup.com',
							    filePath: imageUrl,
							    name: 'file',
							    formData: {
							        'key': key,
									'region': 'SCN',
							        'token': res.data.data.token
							    },
							    success: (res) => {
									console.log(res)
									if (res.statusCode == 200) {
										var json = JSON.parse(res.data)
										var url = _this.$common.photoAddr + json.key
										_this.showPhotoes.push(url)
										_this.sendImageURLtoBase(url)
									}
							    },
							    fail: (err) => {
							        console.log('fail', err);
							    }
							})
						}
						
						
							
				  }
				})
				
			},
		
			
			signItem: function () {
				  let that = this
				  var now = this.$uniApi.formatTime(new Date())
				  var qty = this.signQty == '' ? this.order.order[currentIndex].qty : this.signQty
				  var price = this.signPrice == '' ? this.order.order[currentIndex].price : this.signPrice*100
				  var total = this.$uniApi.accMul(price, qty)
				  var diff = this.order.order[currentIndex].subtotal - total
				  
				  this.order.total -= diff 
				  this.order.order[currentIndex].signforTime = now
				  this.order.order[currentIndex].signforPrice = price
				  this.order.order[currentIndex].signforQty = qty
				  this.order.order[currentIndex].signforSubtotal = total
				  this.order.order[currentIndex].status = 4
				  
				  let orderStatus = this.checkOrderStatus()
				  
				  var map = { "id": currentID, "status":4, "signforTime" : now, "signforPrice" : price,
							"signforQty" : qty, "signforSubtotal" : total}
							
				  var mapOrder = {"id":this.order.id, "total": this.order.total, "status" : orderStatus }
				  
				  uni.request({
				    url: that.$common.serverAddr +'/sales/order/items/edit',
				    data: map,
					method: 'POST',
				    success: function(res) {
						if(res.data.status == 200){
							that.$uniApi.tipMsg('签收成功')
						} else{
							that.$uniApi.tipMsg('签收失败')
						}
				    }
				  })
				
				  uni.request({
				    url: that.$common.serverAddr +'/sales/order/info/edit',
				    data: mapOrder,
				  	method: 'POST',
				    success: function(res) {
				  		if(res.data.status != 200) that.$uniApi.tipMsg('更新订单状态失败')
				    }
				  })
			},
			
			yesReturn: function() {
				this.showReturn = false 
				let now=Date.parse(new Date())
				let item = this.order.order[currentIndex]
				
				var qty = this.inputReturnQty == '' ? item.signforQty : this.inputReturnQty
				var price = this.inputReturnPrice == '' ? item.signforPrice : this.inputReturnPrice*100
				var total = this.$uniApi.accMul(price, qty)
				
				
				let map = {"orderId": this.order.id, "productName":item.productName, 
				"productId":item.productId, "qty":qty, "unit":item.unit, "price":price,
				"subtotal":total,"remarks":this.returnReason, "ctime":now/1000, 
				"customerId": this.order.customerId }
				let that = this
				uni.request({
				  url: that.$common.serverAddr +'/sales/order/return/items/add',
				  data: map,
				  method: 'POST',
				  success: function(res) {
					if(res.data.status == 200){
						that.$uniApi.tipMsg('退货申请成功')
					} else{
						that.$uniApi.tipMsg('退货申请失败')
					}
				  }
				})
				
				uni.request({
				  url: that.$common.serverAddr +'/sales/order/items/edit',
				  data: { "id": currentID, "status":5},
				  method: 'POST',
				  success: function(res) {
					if(res.data.status != 200){
						that.$uniApi.tipMsg('商品状态更新失败')
					}else{
						that.order.order[currentIndex].status = 5
					}
				  }
				})
				
			},
			
			noReturn: function() {
				this.showReturn = false 
			},
			
			confirm: function(id, index, status){
				var text = status == 3 ? '您确定收货吗？' : '您确定退货吗？'
				let that = this
				uni.showModal({
				  title: text,
				  success (res) {
				      if (res.confirm) { 
							currentIndex = index
							currentID = id
							if(status == 3) {
								that.showPop = true 
							}
							if(status == 4) {
								that.showReturn = true
								that.returnTitle = '退回'+ that.order.order[currentIndex].productName
							} 
					}
				  }
				})
			}
		}
	}
</script>

<style>
	
@import url("../orderlist/orderlist.css");
</style>
